package org.yonggan.dmp.utils

import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.security.NoSuchAlgorithmException

import com.alibaba.fastjson.JSON
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.GetMethod
import org.apache.commons.lang.StringUtils

import scala.collection.mutable

/**
  * 百度地图 逆地理编码
  */
object BaiDuMapApi {

  val BAIDU_MAP_API_URL = "http://api.map.baidu.com/geocoder/v2/?"

  private val BAIDU_MAP_API_SK = "nLw9S0Ih7ZNDhrutfuZl5oxfrquO70yA"

  private val BAIDU_MAP_API_AK = "QfygYjaRQCzcOG4tMDydc7fkHztjA5En"

  private val apiUri = "/geocoder/v2/?"


  // 对Map内所有value作utf8编码，拼接返回结果
  @throws[UnsupportedEncodingException]
  private[this] def toQueryString(data: mutable.LinkedHashMap[String, String]): String = {
    val queryString = new StringBuffer
    import scala.collection.JavaConversions._
    for (pair <- data.entrySet) {
      queryString.append(pair.getKey + "=")
      queryString.append(URLEncoder.encode(pair.getValue, "UTF-8") + "&")
    }
    if (queryString.length > 0) queryString.deleteCharAt(queryString.length - 1)
    queryString.toString
  }

  private[this] def MD5(md5: String): String = {
    try {
      val md = java.security.MessageDigest.getInstance("MD5")
      val array = md.digest(md5.getBytes)
      val sb = new StringBuffer
      var i = 0
      while ( {
        i < array.length
      }) {
        sb.append(Integer.toHexString((array(i) & 0xFF) | 0x100).substring(1, 3))

        {
          i += 1;
          i
        }
      }
      return sb.toString
    } catch {
      case e: NoSuchAlgorithmException =>

    }
    null
  }

  /**
    * 组装返回的URL
    *
    * @param lng 经度
    * @param lat 纬度
    */
  private[this] def mapApiUrl(lat: String, lng: String) = {
    // 参数
    val mapParams = new mutable.LinkedHashMap[String, String]()

    val local = lat + "," + lng
    mapParams.put("location", local)
    mapParams.put("output", "json")
    mapParams.put("pois", "1")
    mapParams.put("ak", BAIDU_MAP_API_AK)

    val param = toQueryString(mapParams)

    val sn = getSn(mapParams)
    BAIDU_MAP_API_URL + param + "&sn=" + sn
  }

  /**
    * 提取校验签名信息
    *
    * @return
    */
  @throws[UnsupportedEncodingException]
  private[this] def getSn(paramsMap: mutable.LinkedHashMap[String, String]): String = {

    val paramsStr: String = toQueryString(paramsMap)
    val wholeStr: String = new String("/geocoder/v2/?" + paramsStr + BAIDU_MAP_API_SK)

    val tempStr: String = URLEncoder.encode(wholeStr, "UTF-8")
    MD5(tempStr)
  }


  /**
    * 执行查询 经纬度上 的商业圈
    *
    * @param lat 纬度
    * @param lng 经度
    */
  def excutorQuery(lat: String, lng: String):String = {

    val httpClient = new HttpClient()
    val method = new GetMethod(mapApiUrl(lat, lng))
    val status = httpClient.executeMethod(method)
    // 查询成功
    val json = if (status == 200) method.getResponseBodyAsString else ""

    // 解析json 数据数
    if (StringUtils.isNotEmpty(json)) {
      return business4RespOf(json)
    }
    ""
  }

  /**
    * 返回的Json中获取商圈信息
    *
    * @param json
    */
  private[this] def business4RespOf(json: String) = {

    val tagBuild = new StringBuilder()

    val jsonObject = JSON.parseObject(json)
    val status = jsonObject.getInteger("status")
    if (status == 0) {
      //查询成功
      val result = jsonObject.getJSONObject("result")
      // 提取商圈信息
      val business = result.getString("business")
      if (StringUtils.isEmpty(business)) {
        // 提取周围的商圈标签
        val poisArr = result.getJSONArray("pois")
        for (ids <- 0 until poisArr.size()) {
          // pois
          val tag = poisArr.getJSONObject(ids).getString("tag")
          if (StringUtils.isNotEmpty(tag)) tagBuild.append(tag )

        }
      } else tagBuild.append(business)

    }
    //处理最后的 ，
    var resTag = tagBuild.toString()
    if (resTag.endsWith(",")) resTag = resTag.substring(0, resTag.length - 1)
    resTag
  }

}
